/**
 * 认证状态管理
 * @author Wu.Liang
 * @date 2025-01-21
 */

import { defineStore } from 'pinia'
import authApi from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    // 登录状态
    isLoggedIn: false,
    // 用户token
    token: uni.getStorageSync('token') || '',
    // 刷新token
    refreshToken: uni.getStorageSync('refreshToken') || '',
    // 用户信息
    userInfo: uni.getStorageSync('userInfo') || null,
    // 用户权限
    permissions: [],
    // 用户菜单
    menus: [],
    // 加载状态
    loading: false,
    // 错误信息
    error: '',
    // 自动登录状态
    autoLoginEnabled: uni.getStorageSync('autoLoginEnabled') || false,
    // Token过期时间
    tokenExpireTime: uni.getStorageSync('tokenExpireTime') || 0,
    // 生物识别支持状态
    biometricSupported: false,
    // 生物识别已启用
    biometricEnabled: uni.getStorageSync('biometricEnabled') || false,
    // 请求队列（用于Token刷新时的请求排队）
    requestQueue: [],
    // 是否正在刷新Token
    isRefreshingToken: false
  }),
  
  getters: {
    /**
     * 获取用户ID
     */
    userId: (state) => state.userInfo?.id,
    
    /**
     * 获取用户名
     */
    username: (state) => state.userInfo?.username,
    
    /**
     * 获取用户昵称
     */
    nickname: (state) => state.userInfo?.nickname || state.userInfo?.username,
    
    /**
     * 获取用户头像
     */
    avatar: (state) => state.userInfo?.avatar || '/static/images/default-avatar.png',
    
    /**
     * 获取用户手机号
     */
    phone: (state) => state.userInfo?.phone,
    
    /**
     * 获取用户邮箱
     */
    email: (state) => state.userInfo?.email,
    
    /**
     * 检查是否有菜单权限
     */
    hasMenuPermission: (state) => (menuCode) => {
      return state.permissions.includes(menuCode)
    },
    
    /**
     * 检查是否有角色
     */
    hasRole: (state) => (role) => {
      return state.userInfo?.roles?.some(r => r.code === role)
    },
    
    /**
     * 检查Token是否即将过期
     */
    isTokenExpiringSoon: (state) => {
      if (!state.tokenExpireTime || state.tokenExpireTime === 0) return false
      const now = Date.now()
      const expireTime = state.tokenExpireTime
      // 提前5分钟刷新
      return (expireTime - now) < 5 * 60 * 1000
    },
    
    /**
     * 检查Token是否已过期
     */
    isTokenExpired: (state) => {
      if (!state.tokenExpireTime || state.tokenExpireTime === 0) return false
      return Date.now() > state.tokenExpireTime
    },
    
    /**
     * 检查是否支持生物识别
     */
    isBiometricSupported: (state) => state.biometricSupported,
    
    /**
     * 检查生物识别是否已启用
     */
    isBiometricEnabled: (state) => state.biometricEnabled
  },
  
  actions: {
    /**
     * 用户登录
     * @param {object} loginData 登录数据
     */
    async login(loginData) {
      try {
        this.loading = true
        this.error = ''
        
        console.log('开始登录，登录数据:', loginData)
        const response = await authApi.login(loginData)
        console.log('登录响应:', response)
        
        if (response.code === 200) {
          const data = response.data
          
          // 保存Token信息
          this.token = data.token
          this.refreshToken = data.refreshToken || ''
          
          // 计算Token过期时间
          const expireIn = data.expireIn || 7200 // 默认2小时
          this.tokenExpireTime = Date.now() + expireIn * 1000
          
          // 保存到本地存储
          uni.setStorageSync('token', this.token)
          uni.setStorageSync('refreshToken', this.refreshToken)
          uni.setStorageSync('tokenExpireTime', this.tokenExpireTime)
          
          // 构建用户信息（直接使用登录接口返回的数据）
          const userInfo = {
            id: data.userId || data.user?.id,
            username: data.username || data.user?.username,
            nickname: data.nickname || data.user?.nickname || data.realName || data.user?.realName,
            realName: data.realName || data.user?.realName,
            phone: data.phone || data.user?.phone,
            email: data.email || data.user?.email,
            avatar: data.avatar || data.user?.avatar,
            userType: data.userType || data.user?.userType,
            userTypeName: data.userTypeName || data.user?.userTypeName,
            status: data.status || data.user?.status || 1,
            createTime: data.createTime || data.user?.createTime || new Date().toISOString(),
            updateTime: data.updateTime || data.user?.updateTime || new Date().toISOString(),
            lastLoginTime: data.lastLoginTime || data.user?.lastLoginTime,
            lastLoginIp: data.lastLoginIp || data.user?.lastLoginIp,
            roles: data.roles || data.user?.roles || [],
            permissions: data.permissions || data.menuPermissions || [],
            propertyCompanyId: data.propertyCompanyId || data.user?.propertyCompanyId
          }
          
          // 保存用户信息
          this.userInfo = userInfo
          this.permissions = data.permissions || data.menuPermissions || []
          this.menus = data.menus || []
          
          // 保存到本地存储
          uni.setStorageSync('userInfo', userInfo)
          uni.setStorageSync('userPermissions', JSON.stringify(this.permissions))
          uni.setStorageSync('userMenus', this.menus)
          
          // 同步到userStore
          try {
            const { useUserStore } = await import('@/store/user')
            const userStore = useUserStore()
            userStore.syncUserInfo(userInfo)
            console.log('用户信息已同步到userStore')
          } catch (error) {
            console.warn('同步用户信息到userStore失败:', error)
          }
          
          // 设置登录状态
          this.isLoggedIn = true
          uni.setStorageSync('isLoggedIn', true)
          
          // 延长loading时间，确保信息设置完毕
          await new Promise(resolve => setTimeout(resolve, 1500))
          
          console.log('登录成功，用户信息:', userInfo)
          console.log('登录状态:', this.isLoggedIn)
          console.log('Token:', this.token)
          
          return response
        } else {
          // 优先使用后端返回的错误消息，如果没有则使用默认消息
          this.error = response.message || response.msg || '登录失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '登录失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * App端用户登录（带身份验证）
     * @param {object} loginData 登录数据，包含loginIdentityType字段
     */
    async appLogin(loginData) {
      try {
        this.loading = true
        this.error = ''
        
        console.log('开始App登录，登录数据:', loginData)
        const response = await authApi.appLogin(loginData)
        console.log('App登录响应:', response)
        
        if (response.code === 200) {
          const data = response.data
          
          // 保存Token信息
          this.token = data.token
          this.refreshToken = data.refreshToken || ''
          
          // 计算Token过期时间
          const expireIn = data.expireIn || 7200 // 默认2小时
          this.tokenExpireTime = Date.now() + expireIn * 1000
          
          // 保存到本地存储
          uni.setStorageSync('token', this.token)
          uni.setStorageSync('refreshToken', this.refreshToken)
          uni.setStorageSync('tokenExpireTime', this.tokenExpireTime)
          
          // 构建用户信息（包含身份信息）
          const userInfo = {
            id: data.userId || data.user?.id,
            username: data.username || data.user?.username,
            nickname: data.nickname || data.user?.nickname || data.realName || data.user?.realName,
            realName: data.realName || data.user?.realName,
            phone: data.phone || data.user?.phone,
            email: data.email || data.user?.email,
            avatar: data.avatar || data.user?.avatar,
            userType: data.userType || data.user?.userType,
            userTypeName: data.userTypeName || data.user?.userTypeName,
            status: data.status || data.user?.status || 1,
            createTime: data.createTime || data.user?.createTime || new Date().toISOString(),
            updateTime: data.updateTime || data.user?.updateTime || new Date().toISOString(),
            lastLoginTime: data.lastLoginTime || data.user?.lastLoginTime,
            lastLoginIp: data.lastLoginIp || data.user?.lastLoginIp,
            roles: data.roles || data.user?.roles || [],
            permissions: data.permissions || data.menuPermissions || [],
            propertyCompanyId: data.propertyCompanyId || data.user?.propertyCompanyId,
            // 新增身份信息 - 使用新的4个身份字段
            isOwnerUser: data.isOwnerUser || false,
            isPropertyCompanyUser: data.isPropertyCompanyUser || false,
            isSuperAdmin: data.isSuperAdmin || false,
            isNormalUser: data.isNormalUser || false
          }
          
          // 保存用户信息
          this.userInfo = userInfo
          this.permissions = data.permissions || data.menuPermissions || []
          this.menus = data.menus || []
          
          // 保存到本地存储
          uni.setStorageSync('userInfo', userInfo)
          uni.setStorageSync('userPermissions', JSON.stringify(this.permissions))
          uni.setStorageSync('userMenus', this.menus)
          
          // 保存身份信息到本地存储 - 使用新的4个身份字段
          uni.setStorageSync('isOwnerUser', data.isOwnerUser || false)
          uni.setStorageSync('isPropertyCompanyUser', data.isPropertyCompanyUser || false)
          uni.setStorageSync('isSuperAdmin', data.isSuperAdmin || false)
          uni.setStorageSync('isNormalUser', data.isNormalUser || false)
          
          // 同步到userStore
          try {
            const { useUserStore } = await import('@/store/user')
            const userStore = useUserStore()
            userStore.syncUserInfo(userInfo)
            console.log('App用户信息已同步到userStore')
          } catch (error) {
            console.warn('同步App用户信息到userStore失败:', error)
          }
          
          // 设置登录状态
          this.isLoggedIn = true
          uni.setStorageSync('isLoggedIn', true)
          
          // 延长loading时间，确保信息设置完毕
          await new Promise(resolve => setTimeout(resolve, 1500))
          
          console.log('App登录成功，用户信息:', userInfo)
          console.log('身份信息:', {
            isOwnerUser: data.isOwnerUser,
            isPropertyCompanyUser: data.isPropertyCompanyUser,
            isSuperAdmin: data.isSuperAdmin,
            isNormalUser: data.isNormalUser
          })
          console.log('登录状态:', this.isLoggedIn)
          console.log('Token:', this.token)
          
          return response
        } else {
          // 优先使用后端返回的错误消息，如果没有则使用默认消息
          this.error = response.message || response.msg || 'App登录失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || 'App登录失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 生物识别登录
     */
    async biometricLogin() {
      try {
        this.loading = true
        this.error = ''
        
        // 获取存储的生物识别凭证
        const biometricToken = uni.getStorageSync('biometricToken')
        if (!biometricToken) {
          throw new Error('未找到生物识别凭证，请先使用密码登录')
        }
        
        const response = await authApi.biometricLogin({ token: biometricToken })
        
        if (response.code === 200) {
          this.token = response.data.token
          this.refreshToken = response.data.refreshToken
          this.isLoggedIn = true
          
          // 计算Token过期时间
          const expireIn = response.data.expireIn || 7200
          this.tokenExpireTime = Date.now() + expireIn * 1000
          
          // 保存到本地存储
          uni.setStorageSync('token', this.token)
          uni.setStorageSync('refreshToken', this.refreshToken)
          uni.setStorageSync('tokenExpireTime', this.tokenExpireTime)
          
          // 获取用户信息
          await this.getUserInfo()
          
          return response
        } else {
          this.error = response.message || '生物识别登录失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '生物识别登录失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 启用生物识别
     */
    async enableBiometric() {
      try {
        // 检查设备是否支持生物识别
        const supportResult = await this.checkBiometricSupport()
        if (!supportResult.supported) {
          throw new Error('设备不支持生物识别')
        }
        
        // 获取生物识别凭证
        const response = await authApi.getBiometricToken()
        
        if (response.code === 200) {
          // 保存生物识别凭证
          uni.setStorageSync('biometricToken', response.data.token)
          this.biometricEnabled = true
          uni.setStorageSync('biometricEnabled', true)
          
          return response
        } else {
          throw new Error(response.message || '启用生物识别失败')
        }
      } catch (error) {
        this.error = error.message || '启用生物识别失败'
        throw error
      }
    },
    
    /**
     * 禁用生物识别
     */
    disableBiometric() {
      uni.removeStorageSync('biometricToken')
      this.biometricEnabled = false
      uni.setStorageSync('biometricEnabled', false)
    },
    
    /**
     * 检查生物识别支持
     */
    async checkBiometricSupport() {
      return new Promise((resolve) => {
        // #ifdef APP-PLUS
        uni.checkIsSupportSoterAuthentication({
          success: (res) => {
            const supported = res.supportMode.includes('fingerPrint') || res.supportMode.includes('facial')
            this.biometricSupported = supported
            resolve({ supported, modes: res.supportMode })
          },
          fail: () => {
            this.biometricSupported = false
            resolve({ supported: false, modes: [] })
          }
        })
        // #endif

        // #ifndef APP-PLUS
        // H5/小程序等环境不支持生物识别
        this.biometricSupported = false
        resolve({ supported: false, modes: [] })
        // #endif
      })
    },
    
    /**
     * 用户注册
     * @param {object} registerData 注册数据
     */
    async register(registerData) {
      try {
        this.loading = true
        this.error = ''
        
        const response = await authApi.register(registerData)
        
        if (response.code === 200) {
          return response
        } else {
          this.error = response.message || '注册失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '注册失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 用户登出
     */
    async logout() {
      try {
        this.loading = true
        
        // 调用登出接口
        await authApi.logout()
      } catch (error) {
        console.error('登出接口调用失败:', error)
      } finally {
        // 清除本地状态
        this.clearAuth()
        this.loading = false
        
        // 跳转到登录页面
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    },
    
    /**
     * 获取用户信息（从本地存储获取，不再调用API）
     */
    async getUserInfo() {
      try {
        // 从本地存储获取用户信息
        const userInfo = uni.getStorageSync('userInfo')
        const permissions = uni.getStorageSync('userPermissions')
        const menus = uni.getStorageSync('userMenus')
        
        if (userInfo) {
          this.userInfo = userInfo
          this.permissions = permissions ? JSON.parse(permissions) : []
          this.menus = menus || []
          
          // 同步用户信息到userStore
          try {
            const { useUserStore } = await import('@/store/user')
            const userStore = useUserStore()
            userStore.syncUserInfo(userInfo)
            console.log('从本地存储获取用户信息成功')
          } catch (error) {
            console.warn('同步用户信息到userStore失败:', error)
          }
          
          return userInfo
        } else {
          console.warn('本地存储中没有用户信息，尝试从API获取')
          // 尝试从API获取用户信息
          try {
            const response = await authApi.getUserInfo()
            if (response.code === 200 && response.data) {
              const apiUserInfo = response.data
              this.userInfo = apiUserInfo
              this.permissions = apiUserInfo.permissions || []
              this.menus = apiUserInfo.menus || []
              
              // 保存到本地存储
              uni.setStorageSync('userInfo', apiUserInfo)
              uni.setStorageSync('userPermissions', JSON.stringify(this.permissions))
              uni.setStorageSync('userMenus', this.menus)
              
              // 同步用户信息到userStore
              try {
                const { useUserStore } = await import('@/store/user')
                const userStore = useUserStore()
                userStore.syncUserInfo(apiUserInfo)
                console.log('从API获取用户信息成功')
              } catch (error) {
                console.warn('同步用户信息到userStore失败:', error)
              }
              
              return apiUserInfo
            } else {
              console.warn('API获取用户信息失败，使用默认值')
              // 即使API获取失败，也不清除认证状态，保持登录
              this.userInfo = {}
              this.permissions = []
              this.menus = []
              return {}
            }
          } catch (apiError) {
            console.warn('API获取用户信息异常，使用默认值:', apiError)
            // 网络异常时，不清除认证状态，保持登录
            this.userInfo = {}
            this.permissions = []
            this.menus = []
            return {}
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.error = error.message || '获取用户信息失败'
        // 异常时设置默认值，避免页面崩溃，但保持登录状态
        this.userInfo = {}
        this.permissions = []
        this.menus = []
        return {}
      }
    },
    
    /**
     * 刷新Token
     */
    async refreshTokenAction() {
      if (this.isRefreshingToken) {
        // 如果正在刷新，返回一个Promise等待刷新完成
        return new Promise((resolve, reject) => {
          this.requestQueue.push({ resolve, reject })
        })
      }
      
      this.isRefreshingToken = true
      
      try {
        const response = await authApi.refreshToken()
        
        if (response.code === 200) {
          this.token = response.data.token
          this.refreshToken = response.data.refreshToken
          
          // 计算新的过期时间
          const expireIn = response.data.expireIn || 7200
          this.tokenExpireTime = Date.now() + expireIn * 1000
          
          // 保存到本地存储
          uni.setStorageSync('token', this.token)
          uni.setStorageSync('refreshToken', this.refreshToken)
          uni.setStorageSync('tokenExpireTime', this.tokenExpireTime)
          
          // 处理队列中的请求
          this.requestQueue.forEach(({ resolve }) => resolve(response))
          this.requestQueue = []
          
          return response
        } else {
          // Token刷新失败，清除认证状态
          this.clearAuth()
          throw new Error(response.message || 'Token刷新失败')
        }
      } catch (error) {
        // 处理队列中的请求
        this.requestQueue.forEach(({ reject }) => reject(error))
        this.requestQueue = []
        
        // 清除认证状态
        this.clearAuth()
        throw error
      } finally {
        this.isRefreshingToken = false
      }
    },
    
    /**
     * 修改密码
     * @param {object} passwordData 密码数据
     * @param {string} passwordData.oldPassword 旧密码
     * @param {string} passwordData.newPassword 新密码
     * @param {number} passwordData.userId 用户ID
     */
    async changePassword(passwordData) {
      try {
        this.loading = true
        this.error = ''
        
        const response = await authApi.changePassword(passwordData)
        
        if (response.code === 200) {
          return response
        } else {
          this.error = response.message || '修改密码失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '修改密码失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 获取验证码
     * @param {string} type 验证码类型
     */
    async getCaptcha(type = 'login') {
      try {
        const response = await authApi.getCaptcha(type)
        if (response.code === 200) {
          // 确保返回的数据结构与前端期望一致
          return {
            code: 200,
            data: {
              captcha: response.data.captcha,
              captchaKey: response.data.key, // 后端返回的是key字段
              expireIn: 300
            }
          }
        }
        return response
      } catch (error) {
        this.error = error.message || '获取验证码失败'
        throw error
      }
    },
    
    /**
     * 发送短信验证码
     * @param {object} smsData 短信数据
     */
    async sendSmsCode(smsData) {
      try {
        const response = await authApi.sendSmsCode(smsData)
        return response
      } catch (error) {
        this.error = error.message || '发送短信验证码失败'
        throw error
      }
    },
    
    /**
     * 验证短信验证码
     * @param {object} verifyData 验证数据
     */
    async verifySmsCode(verifyData) {
      try {
        const response = await authApi.verifySmsCode(verifyData)
        return response
      } catch (error) {
        this.error = error.message || '验证短信验证码失败'
        throw error
      }
    },
    
    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
      try {
        const response = await authApi.checkLoginStatus()
        
        if (response.code === 200) {
          this.isLoggedIn = response.data.isLoggedIn
          return response.data
        } else {
          this.isLoggedIn = false
          return { isLoggedIn: false }
        }
      } catch (error) {
        this.isLoggedIn = false
        return { isLoggedIn: false }
      }
    },
    
    /**
     * 设置自动登录
     * @param {boolean} enabled 是否启用
     */
    setAutoLogin(enabled) {
      this.autoLoginEnabled = enabled
      uni.setStorageSync('autoLoginEnabled', enabled)
    },
    
    /**
     * 清除认证状态
     */
    clearAuth() {
      console.log('清除认证状态')
      this.isLoggedIn = false
      this.token = ''
      this.refreshToken = ''
      this.userInfo = null
      this.permissions = []
      this.menus = []
      this.error = ''
      this.tokenExpireTime = 0
      
      // 清除本地存储
      uni.removeStorageSync('token')
      uni.removeStorageSync('refreshToken')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('tokenExpireTime')
      uni.removeStorageSync('autoLoginEnabled')
      uni.removeStorageSync('isLoggedIn')
      uni.removeStorageSync('userPermissions')
      uni.removeStorageSync('userMenus')
      
      // 清除生物识别凭证（但保留启用状态）
      uni.removeStorageSync('biometricToken')
      
      console.log('认证状态清除完成')
    },
    
    /**
     * 初始化认证状态
     */
    async initAuth() {
      try {
        console.log('开始初始化认证状态...')
        
        // 检查本地存储的Token
        const token = uni.getStorageSync('token')
        const refreshToken = uni.getStorageSync('refreshToken')
        const tokenExpireTime = uni.getStorageSync('tokenExpireTime')
        const isLoggedIn = uni.getStorageSync('isLoggedIn')
        
        console.log('本地存储状态:', { 
          hasToken: !!token, 
          hasRefreshToken: !!refreshToken, 
          hasExpireTime: !!tokenExpireTime,
          isLoggedIn: isLoggedIn
        })
        
        // 修复逻辑：只要有token就认为可以恢复登录状态，不需要同时有refreshToken
        if (token) {
          this.token = token
          this.refreshToken = refreshToken || ''
          this.tokenExpireTime = tokenExpireTime || 0
          
          // 检查Token是否过期
          if (this.isTokenExpired && tokenExpireTime) {
            console.log('Token已过期，尝试刷新')
            // Token已过期，尝试刷新
            try {
              if (this.refreshToken) {
                await this.refreshTokenAction()
                await this.getUserInfo()
                this.isLoggedIn = true
                uni.setStorageSync('isLoggedIn', true)
                console.log('Token刷新成功，登录状态已恢复')
              } else {
                console.log('Token已过期且无刷新Token，清除认证状态')
                this.clearAuth()
              }
            } catch (error) {
              console.error('Token刷新失败:', error)
              this.clearAuth()
            }
          } else if (this.isTokenExpiringSoon && tokenExpireTime) {
            console.log('Token即将过期，主动刷新')
            // Token即将过期，主动刷新
            try {
              if (this.refreshToken) {
                await this.refreshTokenAction()
                await this.getUserInfo()
                this.isLoggedIn = true
                uni.setStorageSync('isLoggedIn', true)
                console.log('Token主动刷新成功，登录状态已恢复')
              } else {
                console.log('Token即将过期且无刷新Token，继续使用当前Token')
                await this.getUserInfo()
                this.isLoggedIn = true
                uni.setStorageSync('isLoggedIn', true)
                console.log('登录状态恢复成功')
              }
            } catch (error) {
              console.error('Token刷新失败:', error)
              // 刷新失败时，如果Token还没过期，继续使用
              if (!this.isTokenExpired) {
                await this.getUserInfo()
                this.isLoggedIn = true
                uni.setStorageSync('isLoggedIn', true)
                console.log('Token刷新失败但Token仍有效，登录状态已恢复')
              } else {
                this.clearAuth()
              }
            }
          } else {
            console.log('Token有效，恢复登录状态')
            // Token有效，获取用户信息
            try {
              await this.getUserInfo()
              this.isLoggedIn = true
              uni.setStorageSync('isLoggedIn', true)
              console.log('登录状态恢复成功')
            } catch (error) {
              console.error('获取用户信息失败:', error)
              // Token有效但获取用户信息失败，仍然保持登录状态
              // 只有在明确知道Token无效时才清除
              if (error.message && error.message.includes('401')) {
                console.log('Token无效，清除认证状态')
                this.clearAuth()
              } else {
                // 网络问题或其他错误，保持登录状态
                console.log('网络问题，保持登录状态')
                this.isLoggedIn = true
                uni.setStorageSync('isLoggedIn', true)
              }
            }
          }
        } else if (isLoggedIn === 'true' || isLoggedIn === true) {
          // 如果本地存储显示已登录但没有Token，尝试静默登录
          console.log('检测到登录状态但缺少Token，尝试静默登录')
          try {
            const success = await this.silentLogin()
            if (!success) {
              console.log('静默登录失败，清除认证状态')
              this.clearAuth()
            }
          } catch (error) {
            console.error('静默登录失败:', error)
            this.clearAuth()
          }
        } else {
          console.log('未检测到登录状态')
          this.isLoggedIn = false
        }
      } catch (error) {
        console.error('初始化认证状态失败:', error)
        // 初始化失败时不要清除认证状态，避免误判
      }
    },
    
    /**
     * 静默登录（用于自动登录）
     */
    async silentLogin() {
      try {
        // 检查是否有记住的用户名密码
        const rememberedUsername = uni.getStorageSync('remembered_username')
        const rememberedPassword = uni.getStorageSync('remembered_password')
        
        if (rememberedUsername && rememberedPassword && this.autoLoginEnabled) {
          const loginData = {
            username: rememberedUsername,
            password: rememberedPassword
          }
          
          await this.login(loginData)
          return true
        }
        
        // 如果没有记住的密码，但有Token，尝试验证Token有效性
        if (this.token) {
          try {
            // 尝试调用一个简单的API来验证Token
            const response = await authApi.checkLoginStatus()
            if (response.code === 200 && response.data.isLoggedIn) {
              console.log('Token验证成功，静默登录成功')
              return true
            }
          } catch (error) {
            console.warn('Token验证失败:', error)
          }
        }
        
        return false
      } catch (error) {
        console.error('静默登录失败:', error)
        return false
      }
    },
    
    /**
     * 自动登录功能
     * @returns {Promise<boolean>} 是否自动登录成功
     */
    async autoLogin() {
      try {
        console.log('开始自动登录检查...')
        
        // 检查是否有本地存储的登录信息
        if (!this.token || !this.refreshToken) {
          console.log('本地无登录信息，跳转登录页')
          return false
        }
        
        // 验证token有效性
        const isValid = await this.validateToken(this.token)
        if (isValid) {
          console.log('Token有效，自动登录成功')
          
          // 设置登录状态
          this.isLoggedIn = true
          
          // 加载用户信息
          await this.getUserInfo()
          
          // 加载菜单权限
          await this.getUserMenus()
          
          return true
        } else {
          console.log('Token已过期，尝试刷新')
          
          // 尝试刷新token
          const success = await this.refreshTokenAction()
          if (success) {
            console.log('Token刷新成功，自动登录成功')
            
            // 加载用户信息
            await this.getUserInfo()
            
            // 加载菜单权限
            await this.getUserMenus()
            
            return true
          } else {
            console.log('Token刷新失败，清除本地信息')
            
            // 清除本地登录信息
            this.clearAuth()
            
            return false
          }
        }
      } catch (error) {
        console.error('自动登录失败:', error)
        this.clearAuth()
        return false
      }
    },
    
    /**
     * 验证token有效性
     * @param {string} token 要验证的token
     * @returns {Promise<boolean>} token是否有效
     */
    async validateToken(token) {
      try {
        // 简单检查Token格式
        if (!token || token.length < 10) {
          return false
        }
        
        // 检查Token是否过期（基于本地时间）
        if (this.tokenExpireTime && Date.now() > this.tokenExpireTime) {
          return false
        }
        
        // 对于有Token但没有过期时间的情况，认为Token有效
        // 这样可以避免因为缺少过期时间而误判Token无效
        return true
      } catch (error) {
        console.error('Token验证失败:', error)
        return false
      }
    },
    
    /**
     * 获取用户菜单权限
     */
    async getUserMenus() {
      try {
        const response = await authApi.getUserMenus()
        if (response.code === 200) {
          this.menus = response.data || []
          // 保存到本地存储
          uni.setStorageSync('userMenus', this.menus)
        }
      } catch (error) {
        console.error('获取用户菜单失败:', error)
      }
    }
  }
}) 